package com.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 */
@Configuration
public class MyThreadPoolTaskExecutorConfig implements AsyncConfigurer {

    @Bean("MyExecutor")
    public Executor asyncExecutor() {
        MyThreadPoolTaskExecutor myExecutor = new MyThreadPoolTaskExecutor();
        myExecutor.setCorePoolSize(5);
        myExecutor.setMaxPoolSize(5);
        myExecutor.setQueueCapacity(500);
        myExecutor.setKeepAliveSeconds(60);
        myExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        myExecutor.setThreadNamePrefix("ZFP");
        myExecutor.initialize();
        return myExecutor;
    }


    @Override
    public Executor getAsyncExecutor() {
        return new SimpleAsyncTaskExecutor();
    }

    @Autowired
    private ApplicationContext context;

    @PostConstruct
    public void inspect() {
        Map<String, Executor> execs = context.getBeansOfType(Executor.class);
        System.out.println("===== Executors in context =====");
        execs.forEach((name, exe) -> {
            System.out.println("beanName=" + name + ", class=" + exe.getClass().getName());
        });
        System.out.println("================================");
    }
}
